import sys, os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

import functools
import threading
import time

from flask import jsonify
from flask import request
from service.trade.ths.ths_auto_service_win import ThsAuto
from . import trade

ths_trade_api = ThsAuto()
# 绑定下单界面
ths_trade_api.bind_client()

lock = threading.Lock()
next_time = 0
interval = 0.5


def interval_call(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        global interval
        global lock
        global next_time
        lock.acquire()
        now = time.time()
        if now < next_time:
            time.sleep(next_time - now)
        try:
            rt = func(*args, **kwargs)
        except Exception as e:
            rt = ({'code': 1, 'status': 'failed', 'msg': '{}'.format(e)}, 400)
        next_time = time.time() + interval
        lock.release()
        return rt

    return wrapper


'''
可用余额
'''


@trade.route('/balance', methods=['GET'])
@interval_call
def get_balance():
    ths_trade_api.active_mian_window()
    result = ths_trade_api.get_balance()
    return jsonify(result), 200


'''
持仓信息
'''


@trade.route('/position', methods=['GET'])
@interval_call
def get_position():
    ths_trade_api.active_mian_window()
    result = ths_trade_api.get_position()
    return jsonify(result), 200


'''
委托订单
'''


@trade.route('/orders/active', methods=['GET'])
@interval_call
def get_active_orders():
    ths_trade_api.active_mian_window()
    result = ths_trade_api.get_active_orders()
    return jsonify(result), 200


'''
成交订单
'''


@trade.route('/orders/filled', methods=['GET'])
@interval_call
def get_filled_orders():
    ths_trade_api.active_mian_window()
    result = ths_trade_api.get_filled_orders()
    return jsonify(result), 200


'''
下单买入
'''


@trade.route('/buy', methods=['POST'])
@interval_call
def ths_buy():
    symbol = request.json.get("symbol")
    buy_price = request.json.get("buy_price")
    buy_volume = request.json.get("buy_volume")
    terminal = request.json.get("terminal")
    ths_trade_api.active_mian_window()
    result = ths_trade_api.buy(symbol, buy_volume, buy_price)
    return jsonify(result), 200


'''
下单卖出
'''


@trade.route('/sell', methods=['POST'])
@interval_call
def ths_sell():
    symbol = request.json.get("symbol")
    sell_price = request.json.get("sell_price")
    sell_volume = request.json.get("sell_volume")
    terminal = request.json.get("terminal")
    ths_trade_api.active_mian_window()
    result = ths_trade_api.sell(symbol, sell_volume, sell_price)
    return jsonify(result), 200


'''
取消
'''


@trade.route('/cancel', methods=['POST'])
@interval_call
def ths_cancel():
    entrust_no = request.json.get("entrust_no")
    terminal = request.json.get("terminal")
    ths_trade_api.active_mian_window()
    result = ths_trade_api.cancel(entrust_no)
    return jsonify(result), 200
